package com.kd.juhaowan.base;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kd.juhaowan.http.model.CateModel;
import com.kd.juhaowan.model.LoginUser;
import com.kd.juhaowan.utils.LogUtil;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public final class BoxCacheManager {

    private static final String TAG = BoxCacheManager.class.getSimpleName();
    private static final String FILE_NAME = "dmbox";
    private static final int ACCOUNT_MAX_STORAGE_COUNT = 5;

    private final SharedPreferences sharedPreferences;
    private final SharedPreferences.Editor editor;
    private final List<LoginUser> mUserAccountData;
    private final HashMap<String, Object> mCacheBuffer;

    boolean isLoggedIn = false;
    SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 缓存是否直接打开悬浮窗内容界面，数据来源登录接口返回值，默认值false
     */
    private boolean openWindowContentView;

    public static BoxCacheManager getInstence(Context context){
        if(mInstence == null) {
            synchronized (LogUtil.class) {
                if (mInstence == null) {
                    mInstence = new BoxCacheManager(context);
                }
            }
        }
        return mInstence;
    }

    private volatile static BoxCacheManager mInstence;
    private BoxCacheManager(Context context) {

        sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        mUserAccountData = new ArrayList<LoginUser>();
        mCacheBuffer = new HashMap<String, Object>();
    }

//    public final boolean isOpenWindowContentView() {
//        return openWindowContentView;
//    }
//
//    void setOpenWindowContentView(boolean openWindowContentView) {
//        this.openWindowContentView = openWindowContentView;
//    }

    public boolean isLoggedIn() {
        return isLoggedIn;
    }

    public void removeUserAccount(String  account) {
        List<LoginUser> infos = readAllUserAccountInfo();
        if(infos!=null){
            infos.removeIf(loginUser -> loginUser.getAccount().equals(account));
        }
        saveAllUserAccountInfo(infos);
    }

    public void saveUserAccount(LoginUser info) {
        List<LoginUser> infos = readAllUserAccountInfo();
        int index = -1;
        if(infos!=null){
            for (int i =0;i<infos.size();i++){
                LoginUser user = infos.get(i);
                LogUtil.debugLog(user.getAccount()+"..."+info.getAccount());
                if (!TextUtils.isEmpty(user.getAccount())&&!TextUtils.isEmpty(info.getAccount())&&user.getAccount().equals(info.getAccount())){
                    index=i;
                }
            }
        }

        if(index==-1){
            infos.add(0,info);
        }else {
            infos.remove(index);
            infos.add(0, info);
        }
//        if (!infos.contains(info)) {
//            infos.add(0, info);
//        } else {
//            infos.remove(info);
//            infos.add(0, info);
//        }

        saveAllUserAccountInfo(infos);
    }

    public void saveCatelist(List<CateModel> models){
        mCacheBuffer.put("cateModel",models);
    }
    public List<CateModel> getCateList(){
        if(mCacheBuffer.containsKey("cateModel")){
            return (List<CateModel>)mCacheBuffer.get("cateModel");
        }else {
            return new ArrayList<>();

        }
    }

    public void saveAllUserAccountInfo(List<LoginUser> accountInfos) {
        if (accountInfos != null && !accountInfos.isEmpty()) {
            final int accountSize = accountInfos.size();
            if (accountSize > ACCOUNT_MAX_STORAGE_COUNT) {
                for (int i = accountSize - 1; i > ACCOUNT_MAX_STORAGE_COUNT - 1; i--) {
                    accountInfos.remove(i);
                }
            }

            saveUserAccount();
        }
    }

    private void saveUserAccount() {
        String jsonString = new Gson().toJson(mUserAccountData);
        LogUtil.debugLog(TAG, "saveAllUserAccountInfo ---->jsonString: " + jsonString);
        saveUserAccount(jsonString);
    }

    private void saveUserAccount(String userAccount) {
        if (!TextUtils.isEmpty(userAccount)) {
            try {
                byte[] bytes = userAccount.getBytes("UTF-8");
                byte[] encodeBytes = Base64.encode(bytes, Base64.DEFAULT);
                String str = new String(encodeBytes, "UTF-8");

                mCacheBuffer.put("account", str);
                editor.putString("account", str);
                editor.commit();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    public LoginUser findUserAccountByUsername(String username) {
        List<LoginUser> infos = readAllUserAccountInfo();
        if (infos != null) {
            for (LoginUser info : infos) {
                if (info != null && username.equals(info.getUsername())) {
                    return info;
                }
            }
        }
        return null;
    }

    public LoginUser findUserAccountByUserId(String userId) {
        List<LoginUser> infos = readAllUserAccountInfo();
        if (infos != null) {
            for (LoginUser info : infos) {
                if (info != null && userId.equals(info.getId())) {
                    return info;
                }
            }
        }
        return null;
    }

    public List<LoginUser> readAllUserAccountInfo() {
        if (mUserAccountData.isEmpty()) {
            String jsonString = readUserAccount();
            LogUtil.debugLog(TAG, "readAllUserAccountInfo ---->jsonString: " + jsonString);
            Type listType = new TypeToken<ArrayList<LoginUser>>() {}.getType();
            List<LoginUser> temps = new Gson().fromJson(jsonString, listType);
            if (temps != null) {
                mUserAccountData.addAll(temps);
            }
        }
        return mUserAccountData;
    }

    private String readUserAccount() {
        String accountInfo;
        if (mCacheBuffer.containsKey("account")) {
            accountInfo = (String) mCacheBuffer.get("account");
        } else {
            accountInfo = sharedPreferences.getString("account", "");
            mCacheBuffer.put("account", accountInfo);
        }

        if (!TextUtils.isEmpty(accountInfo)) {
            try {
                byte[] bytes = Base64.decode(accountInfo, Base64.DEFAULT);
                return new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    public void saveCurrentLoginUserUID(String uid) {
        mCacheBuffer.put("uid", uid);
        editor.putString("uid", uid);
        editor.commit();
    }


//    public void saveTabList(List<HomeTabModel> tab){
//        mCacheBuffer.put("tab", tab);
//    }
//    public List<HomeTabModel> readTabList(){
//        if (!mCacheBuffer.containsKey("tab"))return new ArrayList<>();
//        return (List<HomeTabModel>)mCacheBuffer.get("tab");
//
//    }
//
//    public void saveHuatiList(List<HuatiModel> tab){
//        if(tab==null||tab.size()==0)return;
//        mCacheBuffer.put("huati", tab);
//        try {
//            String jsonString = new Gson().toJson(tab);
//            editor.putString("huati", jsonString);
//            editor.commit();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//    }
//
//    public void saveVersionInfo(VersionUpdateInfo tab){
//        if(tab==null)return;
//        mCacheBuffer.put("versioninfo", tab);
//    }
//
//    public VersionUpdateInfo readVersionInfo( ){
//        if (mCacheBuffer.containsKey("versioninfo")) {
//            return  (VersionUpdateInfo) mCacheBuffer.get("versioninfo");
//        }
//        return new VersionUpdateInfo();
//    }

    public void saveHistoryList(String history){
        List<String> temp = readHistoryList();

        if(temp.contains(history)){
            temp.remove(history);
        }
        temp.add(0,history);
        mCacheBuffer.put("history", temp);
        try {
            String jsonString = new Gson().toJson(temp);
            editor.putString("history", jsonString);
            editor.commit();
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    public List<String> readHistoryList() {
        if (mCacheBuffer.containsKey("history")) {
            return (List<String>) mCacheBuffer.get("history");
        } else {
            String huatiString = sharedPreferences.getString("history", "");
            if (!TextUtils.isEmpty(huatiString)) {
                Type listType = new TypeToken<ArrayList<String>>() {
                }.getType();
                List<String> temps = new Gson().fromJson(huatiString, listType);
                mCacheBuffer.put("history", temps);
                return temps;
            } else {
                return new ArrayList<>();
            }
        }
    }



//    public List<HuatiModel> readHuatiList(){
//        if (mCacheBuffer.containsKey("huati")) {
//            return  (List<HuatiModel>) mCacheBuffer.get("huati");
//        } else {
//            String huatiString = sharedPreferences.getString("huati", "");
//            if(!TextUtils.isEmpty(huatiString)){
//                Type listType = new TypeToken<ArrayList<HuatiModel>>() {}.getType();
//                List<HuatiModel> temps = new Gson().fromJson(huatiString, listType);
//                mCacheBuffer.put("huati", temps);
//                return temps;
//            }else {
//                return new ArrayList<>();
//            }
//        }



//    }

    public String readCurrentLoginUserUID() {
        String uid = (String) mCacheBuffer.get("uid");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("uid", "");
            mCacheBuffer.put("uid", uid);
        }
        return uid;
    }


    public String readCurrentOaid(){
        String oaid = (String) mCacheBuffer.get("oaid");
        if (TextUtils.isEmpty(oaid)) {
            oaid = sharedPreferences.getString("oaid", "");
            mCacheBuffer.put("oaid", oaid);
        }
        return oaid;
    }
    public void saveOaid(String oaid){
        mCacheBuffer.put("oaid", oaid);
        editor.putString("oaid", oaid);
        editor.commit();
    }

    public void saveCurrentLoginUserTickit(String ticket) {
        mCacheBuffer.put("ticket", ticket);
        editor.putString("ticket", ticket);
        editor.commit();
    }




    public String readCurrentLoginUserTicket() {
        String uid = (String) mCacheBuffer.get("ticket");
        if (TextUtils.isEmpty(uid)) {
            uid = sharedPreferences.getString("ticket", "");
            mCacheBuffer.put("ticket", uid);
        }
        return uid;
    }

    public void saveGameId(String gameId) {
        mCacheBuffer.put("gameId", gameId);
        editor.putString("gameId", gameId);
        editor.commit();
    }






    public void writeLastLoginType(int loginType) {
        mCacheBuffer.put("loginType", loginType);
        editor.putInt("loginType", loginType);
        editor.commit();
    }

    public void deleteUserAccount(LoginUser accountInfo) {
        if (mUserAccountData.contains(accountInfo)) {
            mUserAccountData.remove(accountInfo);
        }
        saveUserAccount();
    }

    public int readLastLoginType() {
        Object loginType = mCacheBuffer.get("loginType");
        if (loginType == null) {
            loginType = sharedPreferences.getInt("loginType", 1);
            mCacheBuffer.put("loginType", loginType);
        }
        return loginType instanceof Integer ? (Integer) loginType : 1;
    }

    public void writeAutoLogin(boolean auto){
        mCacheBuffer.put("autoLogin", auto);
        editor.putBoolean("autoLogin", auto);
        editor.commit();
    }

    public boolean readAutoLogin() {
        Object loginType = mCacheBuffer.get("autoLogin");
        if (loginType == null) {
            loginType = sharedPreferences.getBoolean("autoLogin", true);
            mCacheBuffer.put("autoLogin", loginType);
        }
        return loginType instanceof Boolean ? (Boolean) loginType : true;
    }






    public void writeNeedBindPhone(boolean isAudult){

        mCacheBuffer.put("needBindPhone", isAudult);
        editor.putBoolean("needBindPhone", isAudult);
        editor.commit();
    }

    public boolean readNeedBindPhone() {
        Object loginType = mCacheBuffer.get("needBindPhone");
        if (loginType == null) {
            loginType = sharedPreferences.getBoolean("needBindPhone", true);
            mCacheBuffer.put("needBindPhone", loginType);
        }
        return loginType instanceof Boolean ? (Boolean) loginType : true;
    }

    private static final String VERSION_UPDATE_DOWNLOAD_ID = "downloadId";

    public void writeVersionDownloadId(long downloadId) {
        mCacheBuffer.put(VERSION_UPDATE_DOWNLOAD_ID, String.valueOf(downloadId));
    }

    public void writeGameDownloadId(String gameid, String downloadid){

        mCacheBuffer.put(VERSION_UPDATE_DOWNLOAD_ID+gameid, downloadid);
        editor.putString(VERSION_UPDATE_DOWNLOAD_ID+gameid, downloadid);
        editor.commit();
    }

    public long readGameDownloadId(String gameId) {
        if(mCacheBuffer.containsKey(VERSION_UPDATE_DOWNLOAD_ID+gameId)){
            String downloadId = (String)mCacheBuffer.get(VERSION_UPDATE_DOWNLOAD_ID+gameId);
            if (!TextUtils.isEmpty(downloadId) && TextUtils.isDigitsOnly(downloadId)) {
                return Long.parseLong(downloadId);
            }
        }

        return 0;
    }



    public long readVersionDownloadId() {
        if(mCacheBuffer.containsKey(VERSION_UPDATE_DOWNLOAD_ID)){
            String downloadId = (String)mCacheBuffer.get(VERSION_UPDATE_DOWNLOAD_ID);
            if (!TextUtils.isEmpty(downloadId) && TextUtils.isDigitsOnly(downloadId)) {
                return Long.parseLong(downloadId);
            }
        }

        return 0;
    }



}
